package com.topnav.mc.schedule.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.js.lib.cache.Cache;
import com.js.lib.cache.SysCache;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DeviceChannel;
import com.topnav.mc.admin.entity.GbServer;
import com.topnav.mc.admin.entity.bean.GbServerBean;
import com.topnav.mc.admin.service.IDeviceChannelService;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.admin.service.IGbServerService;
import com.topnav.mc.admin.service.impl.GbServerServiceImpl;
import com.topnav.mc.gbserverapi.GbServerApi;
import com.topnav.mc.uitls.DeviceOnlineUtils;
import com.topnav.mc.uitls.GbServerUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;


@Component
@Slf4j
public class GbServerOnlineCheckJob implements Job, Serializable {
    @Value("${wvp-server:none}")
    private String wvpServer;
    @Resource(name="sysCache")
    private Cache cache;
    @Autowired
    private IGbServerService gbServerService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceChannelService deviceChannelService;
    @Resource
    private GbServerApi api;
    @Autowired
    private DeviceOnlineUtils deviceOnlineUtils;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //测试WVP是否在配置文件里配置,如果已配置则尝试连接，连接不成功则取数据库里的GbServer
        String url = GbServerUtil.get();
        /* if (url==null && !"none".equals(wvpServer)){
            url = "http://"+wvpServer;
        }
        if (url != null){
            try{
                //尝试连接
                api.info(url);
                GbServerUtil.set(wvpServer);
                return;
            }catch (Exception e){
                if (e.toString().indexOf("Failed to connect to")>-1){
                    GbServerUtil.remove();
                    log.error(e.toString() + ": " + wvpServer);
                }
            }
        }*/

        log.debug(">>>>>> 正在同步国标服务器状态 ......");
        String host = "http://%s:%s";
        String result = null;
        //所有的服务端
        List<GbServerBean> gbServerList = gbServerService.listInfo();
        for(GbServerBean gbServerBean : gbServerList){
            Integer online =0;
            //数据信息不完整
            if (StringUtils.isEmpty(gbServerBean.getLocalIpPort()) && (StringUtils.isEmpty(gbServerBean.getHost()) || StringUtils.isEmpty(gbServerBean.getApiPort()))){
                if (gbServerBean.getOnline() != 0){
                    gbServerBean.setOnline(0);
                    gbServerService.updateById(gbServerBean);
                    continue;
                }
            }
            if (!StringUtils.isEmpty(gbServerBean.getLocalIpPort())){
                url = "http://" + gbServerBean.getLocalIpPort();
            }else{
                url = String.format(host,gbServerBean.getHost(),gbServerBean.getApiPort());
            }

            try{
                online=1;
                result = api.info(url);
            }catch (Exception e){
                if (e.toString().indexOf("Failed to connect to")>-1){
                    log.error(e.toString());
                    online=0;
                }
            }

            if (gbServerBean.getOnline() == online){
                continue;
            }
            //更新服务器的状态
            gbServerBean.setOnline(online);
            gbServerService.updateById(gbServerBean);

            if (online == 0){
                //更新所有设备和通道的离线状态
                QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("gb_server_id",gbServerBean.getId());
                queryWrapper.eq("online",true);
                List<Device> devices = deviceService.list(queryWrapper);
                UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
                UpdateWrapper<DeviceChannel> channelUpdateWrapper = new UpdateWrapper<>();
                for(Device device : devices){
                    deviceUpdateWrapper.clear();
                    deviceUpdateWrapper.set("online",false);
                    deviceUpdateWrapper.eq("id",device.getId());
                    deviceService.update(deviceUpdateWrapper);

                    channelUpdateWrapper.clear();
                    channelUpdateWrapper.set("status",0);
                    channelUpdateWrapper.eq("device_id",device.getId());
                    deviceChannelService.update(channelUpdateWrapper);

                    deviceOnlineUtils.setOffline(device.getCode());
                }

                List<Device> list = deviceService.getAllFromCache();
                for(Device device : list){
                    if (device.getOnline()){
                        device.setOnline(false);
                        deviceService.saveToCache(device);
                    }
                }

            }

        }
    }
}
